import { useState } from 'react';
import { UploadOutlined } from '@ant-design/icons';
import { Button, Progress, Typography, Upload } from 'antd';
import { debounce } from 'lodash';
import { uploadResource } from '@/api/upload';
import { saveOriginFiles } from '@/api/accession';
import { useAccessionMgtContext } from '../../../../contexts/AccessionMgtContext';

const UploadPane = (props: any) => {
  const { activeBatch, updateBatchList } = useAccessionMgtContext();
  // 选中文件列表
  const [uploadList, setUploadList] = useState([]);
  // 上传文件按钮loading状态
  const [uploadLoading, setUploadLoading] = useState(false);
  // 上传进度
  const [uploadPercent, setUploadPercent] = useState(0);

  /**
   * @description: upload组件上传前钩子，处理选中的文件列表
   * @param {File} file
   */
  const beforeUpload = (file: File) => {
    setUploadList((state) => [...state, file]);
    return true;
  };

  const getFileUrl = (name: string, fileUrls: any): string => {
    return fileUrls.find((item: any) => item.name === name)?.url || '';
  };

  /**
   * @description: 上传选中的文件
   * @param {File[]} fileList
   */
  const uploadFileFunc = (fileList: File[]): void => {
    console.log('fileList', fileList);
    const formData = new FormData();
    fileList.forEach((file: File) => {
      formData.append('files', file);
    });

    uploadResource(formData, {
      timeout: 0,
      onUploadProgress: (progress: any) => {
        setUploadPercent(Number(((progress.loaded / progress.total) * 100).toFixed(1)));
      }
    }).then((res: any) => {
      const fileUrlObjs = res.data;
      const params: any = { batchId: activeBatch.id };
      const realFileList = uploadList.map((file: File) => {
        return {
          fileName: file.name,
          filePath: file.webkitRelativePath.split('/').splice(1).join('/'),
          fileSize: file.size,
          fileUrl: getFileUrl(file.name, fileUrlObjs)
        };
      });

      params.originalAtt = {
        level: 0,
        realFileList,
        status: true
      };

      saveOriginFiles(params).then((res: any) => {
        updateBatchList(res.data);
      });
    });
  };

  return (
    <div>
      <Typography.Paragraph>请上传SIP包</Typography.Paragraph>
      <Upload
        beforeUpload={beforeUpload}
        maxCount={1}
        fileList={[]}
        customRequest={debounce(() => {
          setUploadLoading(false);
          uploadFileFunc(uploadList);
        })}
      >
        <Button
          icon={<UploadOutlined />}
          loading={uploadLoading}
          onClick={() => {
            setUploadList([]);
            setUploadPercent(0);
          }}
        >
          点击上传
        </Button>
      </Upload>
      {/* <p>已选择{uploadList.length}个文件</p> */}
      <Progress
        strokeColor={{
          '0%': '#108ee9',
          '100%': '#87d068'
        }}
        percent={uploadPercent}
        status={uploadPercent === 100 ? 'success' : 'active'}
      />
    </div>
  );
};

export default UploadPane;
